const db = wx.cloud.database(
  { env: 'twenty' }
)

function failCallback(err, errMsg) {
  wx.showToast({
    icon: 'none',
    title: '查询记录失败'
  })
  console.error('[数据库] [查询记录] 失败：', err)
}

export function add (collection, postData, succ, fail = failCallback) {
    return new Promise(resolve => {
      wx.showLoading({ title: '数据上传中...' })
      db.collection(collection).add({ data: postData })
        .then(res => {
          wx.hideLoading()
          resolve(res)
        })
        .catch(err => {
          wx.showToast({ icon: 'none', title: '网络连接失败' })
          console.error('[数据库] [新增记录] 失败：', err)
        })
    })
  }

export function remove(collection, _id) {
  return new Promise(resolve => {
    db.collection(collection).doc(_id).remove()
      .then(res => {
        wx.showToast({ title: '删除成功', })
        resolve(res)
      })
      .catch(err => {
        wx.showToast({ icon: 'none', title: '网络连接失败' })
        console.error('[数据库] [删除记录] 失败：', err)
      })
  })
}


export function update(collection, id, updateData) {
  return new Promise(resolve => {
    wx.showLoading({ title: '数据上传中...' })
    db.collection(collection).doc(id).update({ data: updateData })
      .then(res => {
        wx.hideLoading()
        resolve(res)
      })
      .catch(err => console.error('[数据库] [更新记录] 失败：', err))
  })
}

export function query (collection, queryData) {
  wx.showLoading({ title: '数据请求中...' })
  return new Promise(resolve => {
    db.collection(collection).where(queryData).get()
    .then(res => {
      resolve(res.data)
      wx.hideLoading()
    })
    .catch(err => console.error('[数据库] [查询记录] 失败：', err))
  })
}

export function queryByPage (collection, queryData, page, limit = 20) {
  return new Promise(resolve => {
    db.collection(collection)
    .where(queryData).skip(page * limit).limit(limit).get()
    .then(res => { resolve(res.data) })
    .catch(err => { console.error(err) })
  })
}

export function count (collection, postData) {
  return new Promise(resolve => {
    db.collection(collection).where(postData).count()
      .then(res => { resolve(res.total) })
      .catch(err => console.log(err))
  })
}

export function queryAll(collection, condition = {}) {
  wx.showLoading({
    title: '正在载入...',
    mask: true,
   })
  const MAX_LIMIT = 20
  // 等待所有
  return new Promise(resolve => {
    db.collection(collection).count().then(totalRes => {
      const total = totalRes.total
      const batchTimes = Math.ceil(total / MAX_LIMIT)
      const tasks = []
      if (!total) {
        return resolve({ data: [], errMsg: 'no records', })
      }

      for (let i = 0; i < batchTimes; i++) {
        const promise = db.collection(collection).where(condition).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
        tasks.push(promise)
      }

      Promise.all(tasks).then(res => {
        resolve(
          res.reduce((acc, cur) => ({
            data: acc.data.concat(cur.data),
            errMsg: acc.errMsg,
          }))
        )
      }).catch(e => { console.log(e) })
    })
  })
}

